<template>
  <div>
    <div class="headeButton">
      <el-button type="primary" @click="addFn">添加内容</el-button>
    </div>
    <div class="draggable3" style="padding: 20px">
      <el-table row-key="id" :data="tableData" style="width: 100%">
        <template v-for="(item, index) in oldList" :key="`col_${index}`">
          <el-table-column
            v-if="item.type == 1"
            :prop="newList[index].prop"
            :label="item.label"
            align="center"
            show-overflow-tooltip
          >
          </el-table-column>
          <el-table-column
            v-else-if="item.type == 2"
            :prop="newList[index].prop"
            :label="item.label"
            align="center"
          >
            <template #default="scope">
              <el-button type="warning" size="small" @click="changeTableFn(scope.row)"
                >修改</el-button
              >
              <el-popconfirm title="是否确认删除" @confirm="confirmDeleteFn(scope.row)">
                <template #reference>
                  <el-button type="danger" size="small"> 删除 </el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
          <el-table-column
            v-else-if="item.type == 3"
            :prop="newList[index].prop"
            :label="item.label"
            align="center"
          >
            <template #default="scope">
              <el-image :src="scope.row[newList[index].prop]" style="width: 80px; height: 80px" />
            </template>
          </el-table-column>
        </template>
      </el-table>
      <el-pagination
        :current-page="pageData.page"
        :page-size="pageData.size"
        :page-sizes="[10, 20, 30, 40]"
        layout="total, sizes, prev, pager, next"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    <el-dialog
      @close="closeFn"
      v-model="dialogVisibleAdd"
      title="添加"
      width="500"
      :before-close="dialogBeforeCloseFn"
    >
      <div>
        <el-form
          ref="formAddRef"
          :rules="rules"
          :model="formAdd"
          label-width="auto"
          style="max-width: 800px"
        >
          <el-form-item label="图片中文" prop="imageZh">
            <el-upload
              :limit="1"
              :file-list="imageZh"
              :action="baseURL2 + 'api/uploadAvatar'"
              list-type="picture-card"
              :on-success="handSuccessFnZh"
              :on-preview="handlePictureCardPreviewZh"
            >
              <el-icon><Plus /></el-icon>
            </el-upload>
          </el-form-item>
          <el-form-item label="图片英文" prop="imageEn">
            <el-upload
              :limit="1"
              :file-list="imageEn"
              :action="baseURL2 + 'api/uploadAvatar'"
              list-type="picture-card"
              :on-success="handSuccessFnEn"
              :on-preview="handlePictureCardPreviewEn"
            >
              <el-icon><Plus /></el-icon>
            </el-upload>
          </el-form-item>
          <el-form-item label="跳转页面" prop="path">
            <el-select
              v-model="formAdd.path"
              placeholder="请选择"
              size="large"
              style="width: 240px"
            >
              <el-option
                v-for="item in optionsPath"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="标题中文" prop="pathNameZh">
            <el-input v-model="formAdd.pathNameZh" class="imputeWidth" />
          </el-form-item>
          <el-form-item label="标题英文" prop="pathNameEn">
            <el-input v-model="formAdd.pathNameEn" class="imputeWidth" />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer" style="display: flex; justify-content: center">
          <el-button type="primary" @click="confirmFn(0)"> 确定 </el-button>
          <el-button @click="confirmFn(1)">取消</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog v-model="dialogVisibleImage">
      <div style="width: 100%; height: 100%">
        <img style="width: 100%; height: 100%" w-full :src="dialogImage" alt="Preview Image" />
      </div>
    </el-dialog>
  </div>
</template>
 
<script setup >
import { footimage, footimageAdd, footimageDelete, footimageChange, footimageSort } from '@/http/api/WarrantySerach.js'
import Sortable from 'sortablejs'
import { onMounted, reactive, ref } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import { baseURL } from '@/http/request.js'
import { ElMessage } from 'element-plus'
// 只适合做平级的table行和列拖动

let baseURL2 = baseURL
const oldList = ref()
const newList = ref()
const optionsPath = ref([
  {
    label: '首页',
    value: '/'
  }, {
    label: '门店',
    value: '/store'
  }, {
    label: '企业',
    value: '/companyProfile'
  }, {
    label: '新闻',
    value: '/news'
  }, {
    label: '联系我们',
    value: '/contactUs'
  }, {
    label: '个人',
    value: '/my'
  }, {
    label: '产品介绍',
    value: '/product'
  },
])
// 表头
const tableItems = ref([
  {
    label: '中文图片',
    prop: 'imageZh',
    type: 3
  },
  {
    label: '英文图片',
    prop: 'imageEn',
    type: 3
  },
  {
    label: '标题中文',
    prop: 'pathNameZh',
    type: 1
  }, {
    label: '标题英文',
    prop: 'pathNameEn',
    type: 1
  }, {
    label: '操作',
    prop: 'age',
    type: 2
  },
])

// 表体数据
let tableData = ref([])
let formAdd = reactive({})
let imageZh = ref([])
let imageEn = ref([])
let dialogVisibleImage = ref(false)
let pageData = reactive({
  page: 1,
  size: 10
})
const getData = async () => {
  const res = await footimage(pageData)
  tableData.value = res.data.res
  total.value = res.data.total
}
let dialogVisibleAdd = ref(false)
let total = ref(0)
const addFn = () => {
  dialogVisibleAdd.value = true
}
const closeFn = () => {
  dialogVisibleAdd.value = false
}

const rules = reactive({
  imageZh: [
    { required: true, message: '请输入', trigger: 'blur' },
  ],
  imageEn: [
    { required: true, message: '请输入', trigger: 'blur' },
  ],
  path: [
    { required: true, message: '请输入', trigger: 'blur' },
  ],
  pathNameZh: [
    { required: true, message: '请输入', trigger: 'blur' },
  ],
  pathNameEn: [
    { required: true, message: '请上传图片', trigger: 'blur' },
  ],
})
// 行拖拽
const rowDrop2 = function () {
  // 要拖拽元素的父容器 tbody
  const tbody = document.querySelector('.draggable3 .el-table__body-wrapper tbody')
  Sortable.create(tbody, {
    //  可被拖拽的子元素
    draggable: ".draggable3 .el-table__row",
    onEnd ({ newIndex, oldIndex }) {
      // newIndex 拖动到的新的索引
      // oldIndex 没拖动前的索引
      let oldId = tableData.value[oldIndex].id
      let oldSort = tableData.value[oldIndex].sort
      let newId = tableData.value[newIndex].id
      let newSort = tableData.value[newIndex].sort
      const currRow = tableData.value.splice(oldIndex, 1)[0]
      tableData.value.splice(newIndex, 0, currRow)
      footimageSort({ oldId, newId, oldSort, newSort }).then(res => {
        getData()
      })
    }
  })
}
// 上传成功
const handSuccessFnZh = (data) => {
  formAdd.imageZh = data.image_url
}
// 上传成功
const handSuccessFnEn = (data) => {
  formAdd.imageEn = data.image_url
}
let formAddRef = ref()
// 点击添加或这修改按钮
const confirmFn = async (number) => {
  if (number == 0) {
    await formAddRef.value.validate(async (valid, fields) => {
      if (valid) {

        try {
          console.log(formAdd, 55555)
          if (!formAdd.id) {
            await footimageAdd(formAdd)
            ElMessage({
              message: '添加成功',
              type: 'success',
            })
          } else {
            await footimageChange(formAdd)
            ElMessage({
              message: '修改成功',
              type: 'success',
            })
          }
          getData()


        } catch (error) {
          ElMessage({
            message: '失败',
            type: 'error',
          })
        }

      } else {
        ElMessage({
          message: '请补充完整信息',
          type: 'error',
        })
      }
    })


  }

  formAdd = reactive({})
  imageZh.value = []
  imageEn.value = []
  dialogVisibleAdd.value = false
}
// 关闭弹窗
const dialogBeforeCloseFn = () => {
  formAdd = reactive({})
  imageZh.value = []
  imageEn.value = []
  dialogVisibleAdd.value = false
}
// 修改size
const handleSizeChange = (data) => {
  pageData.size = data
  getData()
}
// 修改页数
const handleCurrentChange = (data) => {
  pageData.page = data
  getData()
}
// 确定删除
const confirmDeleteFn = async (data) => {
  try {
    const res = await footimageDelete({ id: data.id })
    ElMessage({
      message: '删除成功',
      type: 'success',
    })
    getData()
  } catch (error) {
    ElMessage({
      message: '删除失败',
      type: 'error',
    })
  }

}
// 修改
const changeTableFn = (data) => {
  dialogVisibleAdd.value = true
  Object.assign(formAdd, data)
  imageZh.value = [{
    url: data.imageZh,
    name: '11'
  }]
  imageEn.value = [{
    url: data.imageEn,
    name: '11'
  }]
}
let dialogImage = ref('')
const handlePictureCardPreviewZh = (data) => {
  dialogVisibleImage.value = true
  dialogImage.value = data.url ? data.url : data.response.image_url
}
onMounted(() => {
  oldList.value = JSON.parse(JSON.stringify(tableItems.value))
  newList.value = JSON.parse(JSON.stringify(tableItems.value))
  rowDrop2()
  getData()
})
</script>
<style lang="scss" scoped>
.imputeWidth {
  width: 260px;
}
.video {
  height: 100px;
  width: 150px;
}
</style>